package com.pp.pingpong;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class GameActivity extends Activity implements SensorEventListener{

	private TextView consola;
	private TextView ownScore;
	private TextView opponentScore;
	private Sensor sensor;
	private SensorManager mSensorManager;
	
	private Button connectBtn;
	private ImageView arrowImg;

	
	private ProgressBar progressBar;
	
	private float mLastX, mLastY, mLastZ;	
	private boolean mInitialized;
	
	private ConnectionManager cm;
	
	private long lastUpdate;
	
	protected PowerManager.WakeLock mWakeLock;
	
	Handler tostaHandler = new Handler();
	Runnable toastRunnable = new Runnable(){

		@Override
		public void run() {
			Toast toast = Toast.makeText(GameActivity.this, "Connection Error", Toast.LENGTH_SHORT);
			toast.show();	
			
		}};
	
	public GameActivity() {	
		
		cm = new ConnectionManager(Config.getInstance().getIpAddress(), Integer.parseInt(Config.getInstance().getPortNumber()));
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);		
		
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);    // Removes title bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);    // Removes notification bar
	    
	    setContentView(R.layout.game_activity);
		
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		connectBtn = (Button) findViewById(R.id.Connect);
		arrowImg = (ImageView) findViewById(R.id.arrow);
		
		consola = (TextView) findViewById(R.id.consola);
		//ownScore = (TextView) findViewById(R.id.own_score);
		//opponentScore = (TextView) findViewById(R.id.opponent_score);
		
		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "tag");
		mWakeLock.acquire();
		
		mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
		sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);	
		
		if (Config.getInstance().getIpAddress() == "" || Config.getInstance().getPortNumber() == "")
		{
			AlertDialog ad = new AlertDialog.Builder(this).create();  
			ad.setCancelable(false); 
			ad.setMessage("Configuration is not filed properly");  
			ad.setButton("OK", new DialogInterface.OnClickListener() {  
			    @Override  
			    public void onClick(DialogInterface dialog, int which) {  
			        dialog.dismiss();    
			        Intent intent = new Intent(GameActivity.this, ConfigurationActivity.class);
			        GameActivity.this.startActivity(intent);
			    }  
			});  
			ad.show();  
		}
		
		
		connectBtn.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				
				Thread thread = new Thread(new Runnable(){

					@Override
					public void run() {
						connectToServer();
						
					}
					
					
				});
				thread.start();
		    	
					
			}
		});		
	}

	public void connectToServer() {	
		
		if ( cm.makeConnection()) {
			Log.d("Connection", "IPAddress "+ cm.socket.getRemoteSocketAddress() + " with port " + cm.socket.getPort());
	    	Log.d("Connection", "Connected");
			mSensorManager.registerListener(GameActivity.this, sensor, SensorManager.SENSOR_DELAY_GAME);			
			lastUpdate = System.currentTimeMillis();			
			Log.d("sensor", "started Sensor");	
			//consola.setText("Conneceted");
			startGame();
		}else {
			progressBar.setVisibility(ProgressBar.INVISIBLE);
			tostaHandler.post(toastRunnable);
				
		}
	}
	
	public void startGame() {
		
		//ownScore.setText("0");
		//opponentScore.setText("0");
	}
	

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		
		
		 float x = event.values[0];
    	 float y = event.values[1];
    	 float z = event.values[2];
    	 
    	 if (!mInitialized) {
    		 mInitialized = true;    	
    		 mLastX = x;
    		 mLastY = y;
    		 mLastZ = z;  				
    		
    	 }else { 
    		 mLastX = x;
    		 mLastY = y;
    		 mLastZ = z;   
    		//float deltaX = mLastX - x;
    		//float deltaY = mLastY - y;    		
    		//float deltaZ = mLastZ - z;
    		
    		long actualTime = System.currentTimeMillis();
	        if ((actualTime - lastUpdate) > 100) 
	        {
	            long diffTime = (actualTime - lastUpdate);
	            lastUpdate = actualTime;
	            
	            //float speed = Math.abs(x+y+z - mLastX - mLastY - mLastZ) / diffTime * 10000;   
	            
	    		String text = "";  
	    		Boolean changed = false;
	    		
	    		int angle = 0;
	    		
	    		if(x>8.0000){
	                Log.d("sensor", "=====LEFT====");
	                //Log.d("sensor", "=====SPEED====  "  + speed);
	                text += " LEFT";                
	                changed = true; 
	                angle = 270;   
	                cm.send("LEFT");
	            }
	            else if(x<-8.0000){
	                Log.d("sensor", "=====RIGHT====");
	                //Log.d("sensor", "=====SPEED====  "  + speed);
	                text += " RIGHT";
	                changed = true;
	                angle = 90;   
	                cm.send("RIGHT");
	            }
	            /*else if (z >9 && z < 10){
	                Log.d("sensor", "=====DOWN====");
	                //Log.d("sensor", "=====SPEED====  "  + speed);
	    			text += " DOWN";
	    			changed = true;
	                angle = 0;    
	            }
	
	            else if (z > -10 && z < -9){
	                Log.d("sensor", "=====UP====");
	                //Log.d("sensor", "=====SPEED====  "  + speed);
	    			text += " UP";
	    			changed = true;
	                angle = 180; 
	            }	
	    		*/
	    		if (changed== true){	   
	    			if (android.os.Build.VERSION.SDK_INT > 11){
		    			arrowImg.setRotation(0);
		    			arrowImg.setRotation(angle);	
		    			
		    			if (angle == 270) {
		    				//cm.send();	    				
		    			}
		    			else if (angle == 0){
		    				//cm.send();
		    			}
						else if (angle == 0){
							//cm.send();    				
						}	    			
						else if (angle == 0){
							//cm.send();
						}	    				
	    			}
	    			
	    		}
	    		
	    		 		
	    		//text += " WITH SPEED " + speed;   
			   // consola.setText(text);
			    
	        }
 
    	 }	
	}

	@Override
	protected void onDestroy() {
		mWakeLock.release();
		super.onDestroy();
	}
	
	
}
